import { Component } from "@angular/core";
import { NavController,App,AlertController} from 'ionic-angular';
import { NativeStorage } from '@ionic-native/native-storage';
import { AppConfig } from '../../../app/app.config';
import { TranslateService } from '@ngx-translate/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';

@Component({
    selector: 'page-reset',
    templateUrl: 'forget.html',
})
export class ForgetPage {
    info = {
        newpwd:'',
        email:'',
        captcha:''
    }
    verify_time=0
    constructor(
        public navCtrl: NavController,
        public app:App,
        public alertCtrl:AlertController,
        public http:HttpClient,
        private translate: TranslateService,
        private storage:NativeStorage
    ) {
        translate.setDefaultLang('en');
    }
    ionViewDidEnter(){
      this.storage.getItem('lang').then(res=>{
          this.translate.use(res)
      })
    }
    alertb(title,subTitle){
        let alert = this.alertCtrl.create({
            title: title,
            subTitle: subTitle,
            buttons: ['OK']
        });
        alert.present();
    }
    goResetPwd(){
        this.http.post(AppConfig.getUrl()+'user/forgetpwd', AppConfig.urlEcode(this.info),{headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) })
            .subscribe( (res) => {
                if(res['code']===101){
                    this.alertb('success','Reset password is successful！you can log in');
                    this.navCtrl.pop();
                }else{
                    this.alertb('Error!',res['msg']);
                }
            })
    }
    goCode(){
        if(this.verify_time===0){
            this.http.post(AppConfig.getUrl()+'tool/sendcaptcha?way=forget', AppConfig.urlEcode({receiver:this.info.email}),{headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) })
            .subscribe( (res) => {
                if(res['code']===101){
                    this.alertb('success','send success,please wait');
                    this.verify_time = 60
                    let timer =setInterval(() => {
                        if(this.verify_time!==0){
                            this.verify_time--
                        }else{
                            clearInterval(timer)
                        }
                    }, 1000);
                }else if(res['code']===202){
                    this.alertb('Error!',res['msg']);
                }
            })
        }else{
            this.alertb('Error','Verification code has been sent, please try again later');
        }
    }
}